import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'iview'
import { setToken, getToken, setTitle } from '@/utils'
Vue.use(Router)

// 将静态路由挂载到路由对象中
const router = new Router({
  routes
})

const LOGIN_PAGE = 'login'

const turnTo = (to, next) => {
  // 判断是否有匹配的页面
  if (to.matched.length > 0) {
    next()
  } else {
    next({ replace: true, name: 'error_404' })
  }
}

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  const token = getToken()
  if (!token && to.name !== LOGIN_PAGE) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE // 跳转到登录页
    })
    iView.LoadingBar.finish()
  } else if (!token && to.name === LOGIN_PAGE) {
    // 未登陆且要跳转的页面是登录页
    next() // 跳转
  } else if (token && to.name === LOGIN_PAGE) {
    // 已登录且要跳转的页面是登录页
    next({
      name: this.$config.homeName // 跳转到homeName页
    })
  } else {
    if (store.state.user.hasGetInfo) {
      turnTo(to, next)
    } else {
      store.dispatch('handleUserInfo').then(() => {
        turnTo(to, next)
      }).catch(() => {
        setToken('')
        next({
          name: LOGIN_PAGE
        })
      })
    }
  }
})

router.afterEach(() => {
  setTitle()
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
